package cn.anquing.jiami.messagedigest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

/**
 * <pre>
 *
 * @description
 * @author wangqq
 * @email wangqq65@gdii-yueyun.com
 * @since 2023/4/20 11:32
 * @copyright 广东美云智数科技有限公司
 * </pre>
 */
public class MyDigest {

    public  static final String MD5 = "MD5";
    public  static final String SHA_1 = "SHA-1";

    public static void main(String[] args) throws UnsupportedEncodingException {
        MyDigest my = new MyDigest();
        // put的顺序不一样，加密的结果是一样的
        HashMap<String, Object> map = new HashMap<>();
        map.put("test5", "test");
        map.put("test6", "test");
        map.put("test1", "test1");
        map.put("test2", "test");
        map.put("test3", "test");
        map.put("test4", "test");
        String s = map.toString();
        my.testDigest(s.getBytes("UTF-8"),MD5);
    }

    public void testDigest(byte[] info,String type) {
        try {
            java.security.MessageDigest messageDigest1 = java.security.MessageDigest.getInstance(type);
            messageDigest1.update(info);
            byte[] digest1 = messageDigest1.digest();
            System.out.println("本信息摘要是1:" + DatatypeConverter.printBase64Binary(digest1));


            //通过某中方式传给其他人你的信息(myinfo)和摘要(digesta) 对方可以判断是否更改或传输正常
            java.security.MessageDigest messageDigest2 = java.security.MessageDigest.getInstance(type);
            messageDigest2.update(info);
            byte[] digest2 = messageDigest2.digest();
            System.out.println("本信息摘要是2:" + DatatypeConverter.printBase64Binary(digest2));

            if (MessageDigest.isEqual(digest1, digest2)) {
                System.out.println("信息检查正常");
            } else {
                System.out.println("摘要不相同");
            }
        } catch (NoSuchAlgorithmException  ex) {
            System.out.println("非法摘要算法");
        }
    }

    public String byte2hex(byte[] b) //二行制转字符串
    {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) hs = hs + "0" + stmp;
            else hs = hs + stmp;
            if (n < b.length - 1) hs = hs + ":";
        }
        return hs.toUpperCase();
    }
}
